package org.csu.mypetstore.api.service.impl;

import org.springframework.util.DigestUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.entity.Account;
import org.csu.mypetstore.api.entity.BannerData;
import org.csu.mypetstore.api.entity.Profile;
import org.csu.mypetstore.api.entity.SignOn;
import org.csu.mypetstore.api.persistence.AccountMapper;
import org.csu.mypetstore.api.persistence.BannerDataMapper;
import org.csu.mypetstore.api.persistence.ProfileMapper;
import org.csu.mypetstore.api.persistence.SignOnMapper;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private BannerDataMapper bannerDataMapper;

    @Autowired
    private ProfileMapper profileMapper;

    @Autowired
    private SignOnMapper signOnMapper;

    //验证登录账号和密码
    @Override
    public CommonResponse<AccountVO> getAccount(String username, String password) {
        QueryWrapper<SignOn> queryWrapper = new QueryWrapper<>();
        //String md5pass = DigestUtils.md5DigestAsHex(password.getBytes());
        queryWrapper.eq("username",username);
        //queryWrapper.eq("password",md5pass);
        queryWrapper.eq("password",password);

        SignOn signOn = signOnMapper.selectOne(queryWrapper);
        if(signOn == null){
            return CommonResponse.createForError("用户名或密码不正确");
        }
        return getAccount(username);
    }

    //由用户名获取用户信息
    @Override
    public CommonResponse<AccountVO> getAccount(String username) {
        Account account = accountMapper.selectById(username);
        Profile profile = profileMapper.selectById(username);
        BannerData bannerData = bannerDataMapper.selectById(profile.getFavouriteCategoryId());
        if(account ==null){
            return CommonResponse.createForError("获取用户信息失败");
        }

        AccountVO accountVO = entityToVO(account,profile,bannerData);
        return CommonResponse.createForSuccess(accountVO);
    }

    //获取密码
    @Override
    public CommonResponse<String> getPassword(String username) {
        SignOn signOn = signOnMapper.selectById(username);
        return CommonResponse.createForSuccess(signOn.getPassword());
    }

    //验证用户名是否存在
    @Override
    public CommonResponse<String> usernameExist(String username) {
        try {
            Account account = accountMapper.selectById(username);
            if (account == null) {
                return CommonResponse.createForSuccessMessage("用户名不存在");
            }
            return CommonResponse.createForSuccessMessage("用户名已存在");
        } catch (Exception e) {
            System.out.println("用户名查询出错"+ e);
            return CommonResponse.createForError("用户名查询出错");
        }
    }

    //新增用户
    @Override
    public CommonResponse<AccountVO> insertAccount(AccountVO accountVO) {
        try {
            Account account = accountVOTOAccount(accountVO);
            Profile profile = accountVOTOAccountProfile(accountVO);
            BannerData bannerData = accountVOTOBannerData(accountVO);
            accountMapper.insert(account);
            profileMapper.insert(profile);
            signOnMapper.insert(accountVOTOAccountSignOn(accountVO));
            //bannerDataMapper.insert(bannerData);
            AccountVO newAccountVO = entityToVO(account,profile,bannerData);
            return CommonResponse.createForSuccess("用户注册成功！",newAccountVO);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.createForError("用户注册失败！");
        }
    }

    //更新用户资料
    @Override
    public CommonResponse<AccountVO> updateAccount(AccountVO accountVO) {
        try {
            Account account = accountVOTOAccount(accountVO);
            Profile profile = accountVOTOAccountProfile(accountVO);
            BannerData bannerData = accountVOTOBannerData(accountVO);
            accountMapper.updateById(account);
            profileMapper.updateById(profile);
            signOnMapper.updateById(accountVOTOAccountSignOn(accountVO));
            bannerDataMapper.updateById(bannerData);
            AccountVO newAccountVO = entityToVO(account,profile,bannerData);
            return CommonResponse.createForSuccess("修改成功", newAccountVO);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.createForError("用户信息更新失败！");
        }
    }

    //获取全部用户资料
    @Override
    public CommonResponse<List<AccountVO>> getAccountList() {
        try{
            List<AccountVO> accountVOList = new ArrayList<>();
            List<Account> accountList = accountMapper.selectList(null);
            for(Account account: accountList){
                Profile profile = profileMapper.selectById(account.getUsername());
                BannerData bannerData = bannerDataMapper.selectById(profile.getFavouriteCategoryId());
                AccountVO accountVO = entityToVO(account,profile,bannerData);
                accountVOList.add(accountVO);
            }
            if(accountVOList.size() == 0){
                return CommonResponse.createForSuccessMessage("当前没有用户信息！");
            }else{
                return CommonResponse.createForSuccess(accountVOList);
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonResponse.createForError("用户信息获取失败！");
        }
    }

    //account,profile,bannerData集成AccountVO
    private AccountVO entityToVO(Account account, Profile profile, BannerData bannerdata){
        AccountVO accountVO = new AccountVO();
        // account 注入
        accountVO.setUsername(account.getUsername());
        // 返回的对象密码清空处理保证安全
        accountVO.setPassword("");
        accountVO.setEmail(account.getEmail());
        accountVO.setFirstName(account.getFirstName());
        accountVO.setLastName(account.getLastName());
        accountVO.setStatus(account.getStatus());
        accountVO.setAddress1(account.getAddress1());
        accountVO.setAddress2(account.getAddress2());
        accountVO.setCity(account.getCity());
        accountVO.setState(account.getState());
        accountVO.setZip(account.getZip());
        accountVO.setCountry(account.getCountry());
        accountVO.setPhone(account.getPhone());

        // profile 注入
        accountVO.setLanguagePreference(profile.getLanguagePreference());
        accountVO.setListOption(profile.isListOption());
        accountVO.setBannerOption(profile.isBannerOption());

        // bannerData 注入
        if (profile.isBannerOption()) {
            accountVO.setFavouriteCategoryId(profile.getFavouriteCategoryId());
            accountVO.setBannerName(bannerdata.getBannerName());
        } else {
            accountVO.setFavouriteCategoryId("");
            accountVO.setBannerName("");
        }

        return accountVO;
    }

    //accountVO获得account
    private Account accountVOTOAccount(AccountVO accountVo)
    {
        Account account = new Account();
        account.setUsername(accountVo.getUsername());
        account.setEmail(accountVo.getEmail());
        account.setFirstName(accountVo.getFirstName());
        account.setLastName(accountVo.getLastName());
        account.setStatus(accountVo.getStatus());
        account.setAddress1(accountVo.getAddress1());
        account.setAddress2(accountVo.getAddress2());
        account.setCity(accountVo.getCity());
        account.setState(accountVo.getState());
        account.setZip(accountVo.getZip());
        account.setCountry(accountVo.getCountry());
        account.setPhone(accountVo.getPhone());
        return account;
    }

    //accountVO获得profile
    private Profile accountVOTOAccountProfile(AccountVO accountVO)
    {
        Profile accountProfile = new Profile();
        accountProfile.setUsername(accountVO.getUsername());
        accountProfile.setFavouriteCategoryId(accountVO.getFavouriteCategoryId());
        accountProfile.setLanguagePreference(accountVO.getLanguagePreference());
        accountProfile.setBannerOption(accountVO.isBannerOption());
        accountProfile.setListOption(accountVO.isListOption());
        return accountProfile;
    }

    //accountVO获取signOn
    private SignOn accountVOTOAccountSignOn(AccountVO accountVO)
    {
        SignOn accountSignOn = new SignOn();
        //String md5pass = DigestUtils.md5DigestAsHex(accountVO.getPassword().getBytes());
        accountSignOn.setUsername(accountVO.getUsername());
        //accountSignOn.setPassword(md5pass);
        accountSignOn.setPassword(accountVO.getPassword());
        return accountSignOn;
    }

    //accountVO获取bannerData
    private BannerData accountVOTOBannerData(AccountVO accountVO)
    {
        BannerData bannerData = new BannerData();
        bannerData.setFavouriteCategoryId(accountVO.getFavouriteCategoryId());
        bannerData.setBannerName(accountVO.getBannerName());
        return bannerData;
    }
}
